package com.example.parsexml;

import android.util.Log;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
 * project:
 * author: wzq
 * date: 2014/7/31
 * description:
 */
public class Dom {
    public static List<ModelStu> parse(InputStream is) {
        Document document = null;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            document = builder.parse(is);
        } catch(IOException e) {
            e.printStackTrace();
        } catch(ParserConfigurationException e) {
            e.printStackTrace();
        } catch(SAXException e) {
            e.printStackTrace();
        }

        // document -> 数据模型 处理dom要相当小心
        List<ModelStu> stuList = new ArrayList<ModelStu>();
        if(document != null) {
            Element element = document.getDocumentElement();
            NodeList nodeList = element.getElementsByTagName("stu");
            for(int i = 0; i < nodeList.getLength(); i++) {
                // id name age sex
                Element aStu = (Element) nodeList.item(i);
                ModelStu modelStu = new ModelStu();
                modelStu.setId(aStu.getAttribute("id"));//TODO:属性
                NodeList childNodes = aStu.getChildNodes();

                for(int j = 0; j < childNodes.getLength(); j++) {
                    Node node = childNodes.item(j);
                    if(node.getNodeType() != Node.ELEMENT_NODE) {
                        continue;
                    }
                    Element e = (Element) node;
                    Log.i("dom", "nodeName="
                                  + e.getNodeName()
                                  + ", localName=" + e.getLocalName()
                                  + ", tagName=" + e.getTagName());
                    if("name".equals(e.getNodeName())) {
                        modelStu.setName(e.getFirstChild().getNodeValue());
                    } else if("sex".equals(e.getNodeName())) {
                        modelStu.setSex(e.getFirstChild().getNodeValue());
                    } else if("age".equals(e.getNodeName())) {
                        int age = Integer.parseInt(e.getFirstChild().getNodeValue());
                        modelStu.setAge(age);
                    }
                }

                // add to list
                stuList.add(modelStu);
            }
        }
        return stuList;
    }
}
